import axios from 'axios'
import nodePath from 'path'
import { message, notification } from 'ant-design-vue'
import * as auth from './auth'

let router
let isUseGlobalNotification
const unuseGlobalNotificationApiList = [
  '/api/user/login'
]

const instance = axios.create({
  baseURL: '', // 移除前缀，可直接兼容任意代理接口
  timeout: 10e3
})

instance.interceptors.request.use(config => {
  const token = auth.getToken()
  const currentApi = nodePath.join(config.baseURL, config.url)
  isUseGlobalNotification = !unuseGlobalNotificationApiList.includes(currentApi)

  if (isUseGlobalNotification && !token) {
    message.warning('认证 token 已过期，请重新登录')
    router.push('/login')
  }

  if (token) {
    config.headers.Authorization = `Bearer ${ token }`
  }

  return config
}, error => Promise.reject(error))

instance.interceptors.response.use(response => {
  const body = response.data

  if (body.code !== 200 || response.status !== 200) {
    const errorMessage = body.data || body.msg

    notification.error({
      message: '异常提示',
      description: errorMessage
    })

    return Promise.reject(new Error({ // 模拟一个 Error 对象
      message: errorMessage,
      response: response
    }))
  }

  return response
}, error => {
  isUseGlobalNotification && notification.error({
    message: '异常提示',
    description: error.message || error.toString()
  })
  return Promise.reject(error)
})

export const initAPI = r => (router = r)
/**
 * - when method includes `get,delete,head,options`, use Prop `params`
 * - when method includes `post,put,patch`, use Prop `data`
 */
export const createAPI = (url, method, config) => instance({ url, method, ...config })
